package com.chuantou.yuba;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.chuantou.yuba.dao.MessageDao;
import com.chuantou.yuba.ui.SystemMessageActivity;
import com.chuantou.yuba.util.AccountManager;
import com.easemob.EMCallBack;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;

public class YBApp extends Application {
	private static YBApp sApp;
	private BDLocation mLocation = null;
	private LocationClient mLocationClient;
	private BDLocationListener mExtendLocationListener;
	private int mReceiveLocationCount = 0;
	public static String BAIDU_KEY = null;
	public static YBHXSDKHelper hxSDKHelper = new YBHXSDKHelper();
	public static IWXAPI sWXApi;

	@Override
	public void onCreate() {
		super.onCreate();
		sApp = this;
		BAIDU_KEY = getMetaDataValue("com.baidu.lbsapi.API_KEY");
		AccountManager.getInstance(getApplicationContext());
		mLocationClient = new LocationClient(getApplicationContext());
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType("bd09ll");
		option.setScanSpan(1000);// 设置发起定位请求的间隔时间为1000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
		// 只有主进程才初始化环信相关信息
		if (isMainProcess()) {
			hxSDKHelper.onInit(getApplicationContext());
			// 注册一个透传消息的BroadcastReceiver
			IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
			cmdMessageIntentFilter.setPriority(3);
			registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);
		}
	}

	public static YBApp get() {
		return sApp;
	}

	public BDLocationListener mLocationListener = new BDLocationListener() {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location != null) {
				mLocation = location;
			}
			if (mExtendLocationListener != null) {
				mExtendLocationListener.onReceiveLocation(mLocation);
			}
			if (mReceiveLocationCount >= 3) {
				stopLocate(true);
			}
			mReceiveLocationCount++;
			// TODO 获取到位置后，如果是登录状态，刷新一次token
			if (isMainProcess()) {
				// TODO upload position

			}
		}
	};

	public void startLocate(BDLocationListener listener) {
		mExtendLocationListener = listener;
		mLocationClient.registerLocationListener(mLocationListener);
		mLocationClient.start();
	}

	public void stopLocate(boolean forceStop) {
		mExtendLocationListener = null;
		if (forceStop || mLocation != null) {
			mLocationClient.stop();
			mLocationClient.unRegisterLocationListener(mLocationListener);
			mReceiveLocationCount = 0;
		}
	}

	public BDLocation getLocation() {
		return mLocation;
	}

	private String getCurProcessName(Context context) {
		int pid = android.os.Process.myPid();
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}
		return null;
	}

	private String getMetaDataValue(String name) {
		try {
			ApplicationInfo applicationInfo;
			applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			if (applicationInfo != null && applicationInfo.metaData != null) {
				return String.valueOf(applicationInfo.metaData.get(name));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private boolean isMainProcess() {
		return getPackageName().equals(getCurProcessName(getApplicationContext()));
	}

	/**
	 * 退出登录,清空数据
	 */
	public void logout(final EMCallBack emCallBack) {
		// 先调用sdk logout，在清理app中自己的数据
		hxSDKHelper.logout(emCallBack);
		AccountManager.logout(sApp);
	}

	/**
	 * 透传消息BroadcastReceiver
	 */
	private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			abortBroadcast();
			// 获取cmd message对象
			String msgId = intent.getStringExtra("msgid");
			EMMessage message = intent.getParcelableExtra("message");
			// 获取消息body
			CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
			String action = cmdMsgBody.action;// 获取自定义action
			if ("feedback".equals(action) || "report".equals(action) || "fishing_place".equals(action) || "fishing_shop".equals(action)) {
				String msg = null;
				try {
					msg = message.getStringAttribute("msg", null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!TextUtils.isEmpty(msg)) {
					MessageDao.insertMessage(sApp, msgId, action, msg, System.currentTimeMillis());
					sendNotification(msg);
				}
			} else if ("add_blacklist".equals(action)) {
				String uid = message.getStringAttribute("hxuid", "");
				if (!TextUtils.isEmpty(uid)) {
					EMChatManager.getInstance().deleteConversation(uid);
				}
			}
		}
	};

	private void sendNotification(String message) {
		String title = sApp.getString(R.string.app_name);
		Intent notificationIntent = new Intent(this, SystemMessageActivity.class); // 点击该通知后要跳转的Activity
		NotificationManager notificationManager = (NotificationManager) sApp.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, title, System.currentTimeMillis());
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 200, notificationIntent, 0);
		notif.setLatestEventInfo(this, title, message, pendingIntent);
		notif.flags = Notification.FLAG_AUTO_CANCEL;
		notif.defaults = Notification.DEFAULT_SOUND;
		notificationManager.notify(100, notif);
	}

	protected void finalize() throws Throwable {
		try {
			unregisterReceiver(cmdMessageReceiver);
		} catch (Exception e) {
		}
	};
}
